package mudbconnection;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;

import muobject.Student;
import muobject.User;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component("DBUsersService")
public class DBUsersService implements DBUsers{

	private JdbcTemplate jdbct;

	@Autowired
	public DBUsersService(DataSource jdbct) {
		super();
		this.jdbct = new JdbcTemplate(jdbct);
	}
	
	public User getLoginUser(String account, String password){
		try{
			User user = (User)jdbct.queryForObject("Select * from Users where Account=? and Password=?",
				    new Object[]{ account, password }, new UserMapper());
			return user;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return null;
		}
	}
	
	public User getTopUser(){
		try{
			User user = (User)jdbct.queryForObject("Select top 1 * from Users", new UserMapper());
			return user;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return null;
		}
	}
	
	public boolean setAccountPassword(String account, String password, int uid){
		try{
			if(!(account.equals("") & password.equals(""))){
				jdbct.update(" update Users set Account = ?, Password = ? where Uid = ? ",
				new Object[]{ account, password, uid });
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}
	}
	
	class UserMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = null;
			try {
				user = new User(rs.getInt("Uid"),rs.getString("Account"), rs.getString("Password")
            			,rs.getString("Sno") , rs.getString("Type"), rs.getInt("TypeNo")
            			, rs.getDate("CreateDate"), rs.getDate("UpdateDate"));
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			return user;
		}
	}
}
